﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


// Je change un truc...
namespace JobUtil.Controls
{
    public partial class ChangeExtensions : UserControl
    {
        public ChangeExtensions()
        {
            InitializeComponent();

            cb_chooseExt.BeginUpdate();
            cb_chooseExt.Items.Add(".sql");
            cb_chooseExt.Items.Add(".txt");
            cb_chooseExt.SelectedIndex = cb_chooseExt.Items.IndexOf(".sql");


            btn_run.Enabled = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            pBar.Minimum = 0;
            pBar.Maximum = 100;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void choose_folder_Click(object sender, EventArgs e)
        {
            
            if (fdb_source.ShowDialog() == DialogResult.OK)
            {
                this.tb_source.Text = fdb_source.SelectedPath;
            }
            
            if (this.tb_source.Text != "") 
                this.btn_run.Enabled = true;
        }

        private void btn_run_Click(object sender, EventArgs e)
        {

                // RUN !
                string path_source = this.tb_source.Text;

                // return list
                var filereturn = read_dir(path_source);
                string new_path;

                // On recoit l'index de l'extension choisie
                int index = cb_chooseExt.SelectedIndex;
                decimal i = 0;
                decimal progress = 0;
                int nb_files = filereturn.Count;

                // On remet la progress barre à 0 au cas ou elle aurait déjà servi
                pBar.Refresh();

                try
                {
                    // Pour chaque path dans la liste, on change l'extension à cb_chooseExt.Items[index].ToString() (l'extension)

                    foreach (var file in filereturn)
                    {
                        new_path = Path.ChangeExtension(file, cb_chooseExt.Items[index].ToString());
                        Microsoft.VisualBasic.FileSystem.Rename(file, new_path);


                        // Texte
                        tb_list.AppendText(file.ToString() + " renamed." + "\r\n");


                        // Progressbar
                        i = i + 1;

                        // Calculate pbar Value
                        progress = (i / nb_files) * 100;
                        pBar.Value = decimal.ToInt32(Math.Round(progress, 0));

                        // Writing text into pbar
                        pBar.CreateGraphics().DrawString(pBar.Value.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(pBar.Width / 2 - 10, pBar.Height / 2 - 7));

                    }

                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
         

        }

        private List<string> read_dir(string path)
        {

            List<string> listfile = new List<string>();

            try
            {
                // on récupère les fichiers dans la source
                foreach (var file in Directory.GetFiles(path))
                {
                    listfile.Add(file);
                }

                // Si l'utilisateur veut que les dossiers enfants soient traités
                if (cb_recursivity.Checked == true)
                {

                    // On fait le listing
                    // pour chaque dossier de la source, on ajoute les fichiers
                    foreach (var d in Directory.GetDirectories(path))
                    {
                        foreach (var file in Directory.GetFiles(d))
                        {
                            listfile.Add(file);
                        }
                        var recursiv = read_dir(d);
                    }
                }
                // on retourne la liste
                return listfile;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                return null;
            }

        }


        private void btn_clear_Click(object sender, EventArgs e)
        {
            tb_list.Clear();
            pBar.Value = 0;
            pBar.Refresh();

        }

        private void btn_clipboard_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(tb_list.Text);
        }

        private void btn_savelog_Click(object sender, EventArgs e)
        {

            // Sfd_log params
            sfd_log.Title = "Indiquez un nom de fichier";
            sfd_log.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            sfd_log.OverwritePrompt = true;
            sfd_log.FilterIndex = 1;

            if (sfd_log.ShowDialog() == DialogResult.OK)
            {
                if (sfd_log.FileName != "")
                {
                    // create a file stream, where "c:\\testing.txt" is the file path
                    FileStream fs = new FileStream(sfd_log.FileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);

                    // create a stream writer
                    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.ASCII);

                    // write to file (buffer)
                    sw.Write(tb_list.Text);

                    // flush buffer (so the text really goes into the file)
                    sw.Flush();

                    // close stream writer and file
                    sw.Close();
                    fs.Close();
                }
            }
        }

        private void tb_source_TextChanged(object sender, EventArgs e)
        {
            if (this.tb_source.Text != "") { this.btn_run.Enabled = true; } else { this.btn_run.Enabled = false; }
                
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void ChangeExtensions_Load(object sender, EventArgs e)
        {

        }

        private void fdb_source_HelpRequest(object sender, EventArgs e)
        {

        }

       
    }
}
